package com.edu.neusoft.elec_shop.controller;

import com.edu.neusoft.elec_shop.domain.User;
import com.edu.neusoft.elec_shop.service.UserService;
import com.edu.neusoft.elec_shop.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/users")
@Api(tags = "用户管理接口")
public class UserController {

    @Autowired
    private UserService userService;

    // 新用户注册
    @PostMapping("/register")
    @ApiOperation(value = "新用户注册", notes = "接收用户对象作为请求体，将用户信息添加到系统中进行注册。")
    public AjaxResult registerUser(@RequestBody User user) {
        try {
            int result = userService.register(user);
            if (result > 0) {
                return AjaxResult.success("用户注册成功");
            } else {
                return AjaxResult.error("用户注册失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("用户注册失败：" + e.getMessage());
        }
    }

    // 用户登录
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "接收用户对象作为请求体，验证用户名和密码是否匹配，若匹配则返回对应的用户信息，否则返回 null")
    public AjaxResult loginUser(@RequestBody User user) {
        try {
            User existingUser = userService.getUserById(user.getUserId());
            if (existingUser!= null && existingUser.getPassword().equals(user.getPassword())) {
                return AjaxResult.success("登录成功", existingUser);
            } else {
                return AjaxResult.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return AjaxResult.error("登录出现异常：" + e.getMessage());
        }
    }

    // 用户修改个人信息
    @PutMapping("/{userId}")
    @ApiOperation(value = "用户修改个人信息", notes = "根据传入的用户ID以及请求体中的用户信息，更新对应用户的个人信息")
    public AjaxResult updateUserInfo(@PathVariable("userId") @Valid Long userId, @RequestBody User record) {
        try {
            record.setUserId(userId);
            int result = userService.updateByUserId(record);
            if (result > 0) {
                return AjaxResult.success("用户信息修改成功");
            } else {
                return AjaxResult.error("用户信息修改失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("用户信息修改失败：" + e.getMessage());
        }
    }

    // 用户注销账户
    @DeleteMapping("/{userId}")
    @ApiOperation(value = "用户注销账户", notes = "根据传入的用户ID，删除对应的用户账户信息")
    public AjaxResult deleteUserAccount(@PathVariable("userId") @Valid Long userId) {
        try {
            int result = userService.deleteByUserId(userId);
            if (result > 0) {
                return AjaxResult.success("用户账户注销成功");
            } else {
                return AjaxResult.error("用户账户注销失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("用户账户注销失败：" + e.getMessage());
        }
    }
}